class PurchasesController < ApplicationController
  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @purchase_pages, @purchases = paginate :purchases, :per_page => 10
  end

  def show
    @purchase = Purchase.find(params[:id])
  end

  def new
    @purchase = Purchase.new
    session[:purchase_items] = nil
  end

  def create
    @purchase = Purchase.new(params[:purchase])
    if @purchase.save
      session[:purchase] = @purchase
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  def add_item
    session[:purchase_items] ||= []
    session[:purchase_items] << PurchaseItem.new(params[:purchase_item])
    render :partial => "purchase_item_list"
  end
  
  def edit
    @purchase = Purchase.find(params[:id])
  end

  def update
    @purchase = Purchase.find(params[:id])
    if @purchase.update_attributes(params[:purchase])
      flash[:notice] = 'Purchase was successfully updated.'
      redirect_to :action => 'show', :id => @purchase
    else
      render :action => 'edit'
    end
  end

  def destroy
    Purchase.find(params[:id]).destroy
    redirect_to :action => 'list'
  end

end
